package com.koudai.finance.exception;

import com.koudai.finance.enums.ResultCode;
import com.koudai.finance.web.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * @Description: 异常处理
 * @author: ls
 * @Date: 2020/6/10 10:12
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * @Description: 自定义业务异常
     * @author: ls
     * @Date: 2020/7/14 20:38
     */
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public ApiResult handleCustomException(BusinessException e) {
        return ApiResult.failure(e.getCode(), e.getMessage());
    }

    /**
     * @Description: 其他异常
     * @author: ls
     * @Date: 2020/7/14 20:39
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ApiResult handleException(Exception e) {
        log.error("发生异常！原因是:", e);
        BindingResult result;
        if (e instanceof MethodArgumentNotValidException) {
            result = ((MethodArgumentNotValidException) e).getBindingResult();
            return ApiResult.failure(ResultCode.PARAM_IS_INVALID.getCode(), result.getFieldError().getDefaultMessage());
        }
        if (e instanceof BindException) {
            result = ((BindException) e).getBindingResult();
            return ApiResult.failure(ResultCode.PARAM_IS_INVALID.getCode(), result.getFieldError().getDefaultMessage());
        }
        if (e instanceof ConstraintViolationException) {
            Set<ConstraintViolation<?>> constraintViolations = ((ConstraintViolationException) e).getConstraintViolations();
            for (ConstraintViolation<?> violation : constraintViolations) {
                return ApiResult.failure(ResultCode.PARAM_IS_INVALID.getCode(), violation.getMessage());
            }
        }
        if (e instanceof IllegalArgumentException) {
            return ApiResult.failure(ResultCode.PARAM_IS_INVALID.getCode(), e.getMessage());
        }
        return ApiResult.failure(ResultCode.SYSTEM_INNER_ERROR);
    }

}
